import {WebSocketConfig} from './WebsocketConfig'
import Cmd from '../config/Cmd'
import {mutations_const} from "../config/StoreConstant";
let parse = function (str) {

  let res = [];
  if (str.length !== 12) {

    return [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
  }
  for (let i = 0; i < str.length; i += 2) {

    let temp = str.substr(i, 2);
    res.push(eval("0x" + temp))
  }
  return res;
}
let macStringfy = function (mac) {

  let res = "";
  for (let i = 0; i < mac.length; i++) {
    var temp = mac[i]&0xff;
    res += prefixInteger(temp.toString(16), 2);
  }
  return res;
}
let handlers = {
  parse,
  macStringfy,
  onlineStateHandler(data,store) {

    let member = store.getters.getMemberByDeviceNum(macStringfy(data["pen-mac-addr"]).slice);
    member.online = data["para"] !== 0;
    window.vueMain.$store.commit(mutations.UPD_CLASS_MEMBERS_SINGLE, member)
  },
  writeHanlder(data){

    let serialNo = WebSocketConfig.macStringfy(data["pen-mac-addr"]);
    let para = data.para;

    let strokeArr = [];
    let page = data.para['code-page'];
    for (let i = 0; i < data.para['xy-dot-array'].length; i++) {

      let dot = data.para['xy-dot-array'][i];
      strokeArr.push(decodePage(page,dot.x,dot.y))
    }
    para['xy-dot-array'] = strokeArr;
    if(strokeArr[0]){

      para["code-page"] = strokeArr[0].pageCode;
    }

    StrokeStore.addStroke(serialNo,para);
    let member = getStoreMemberBySerialNo(serialNo);
    let operation = window.vueMain.$store.state.operation;


    if(operation.hasOperation){

      window.client.publish(`server/device/`, JSON.stringify({
        //id：随机值，便于查找消息，查问题
        "id": Utils.getMqttSerialNo(),
        //设备类型
        "device-type":2,
        //code值，上传数据
        "code": "0201",
        //接收标记
        "packet-type": "response",
        //指令标记字段，服务端返回，直接放入
        "answer-label": operation.answerLabel,
        data: {
          answerRawData:data.para,
          "memberId":member.memberId
        }
        //上传数据笔对应用户id
      }))
      //统计学生的作答时间
      if(!member.answerBeginTime){

        member.answerBeginTime = para["stroke-start-time-s"]*1000 + para["stroke-start-time-ms"];
      }

      member.answered = true;
      member.answerEndTime = para["stroke-start-time-s"]*1000 + para["stroke-start-time-ms"] + para["xy-dot-array"].length*7;
      window.vueMain.$store.commit(mutations_const.UPD_CLASS_MEMBERS_SINGLE,member)

    }

    $Event.emit("pen-write"+serialNo,para)

  }
}

export {macStringfy,parse}
